import pg

from dao import DaoSpecies, DaoTemplate

import ConfigParser


class ApplicationContext:
    def __init__(self, configFile):
        # load the dbconfig file
        self._load_config(configFile)
        
        # create a database connection
        host = self.dbconfig['host']
        port = self.dbconfig['port']
        database = self.dbconfig['database']
        dbuser = self.dbconfig['user']
        dbpassword = self.dbconfig['password']
        self._dbconnection = pg.connect(database, host, int(port), None, None, dbuser, dbpassword)
        
        # init DAOs
        self._init_daos()
        
    def _load_config(self, file):
        parser = ConfigParser.RawConfigParser({'host':'localhost', 'port':5432, 'database':'postgres', 'user':'postgres', 'password':'postgres', 'fftlen':256, 'samplespersecond':100, 'fbpp':10})
        parser.read(file)
        self.dbconfig = dict(parser.items('database'))
        self.fftconfig = dict(parser.items('fft'))
        
    def _init_daos(self):
        self.species_dao = DaoSpecies(self._dbconnection)
        self.template_dao = DaoTemplate(self._dbconnection)
        
    def get_dbconnection(self):
        return self._dbconnection

    def db_disconnect(self):
        self._dbconnection.close()
